//  数字取万
const parseNum = num => {
  if (!num) {
    return 0
  }
  num = +num;
  if (num < 10000) return num;
  const obj = new Number(num / 10000);
  let rt = obj.toFixed(1);
  const arr = rt.split('.');
  if (+arr[1] === 0) {
    rt = arr[0]
  }
  return `${rt}万`;
};

//  格式化时间
const parseTime = (time, cFormat) => {
  if (arguments.length === 0) {
    return null;
  }
  if ((time + '').length === 10) {
    time = +time * 1000
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    date = new Date(parseInt(time));
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1];
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
}

// 格式化rich-text
const formatRichText = html => {
  let newContent = html.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;"').replace(
    /\<div style=\"/gi, '<div style="width:100%;word-break:break-all;word-wrap:normal;').replace(/\s{2,}/g, "")
  return newContent
}

const timeDifference = (timer) => {
  const mouth = parseInt((timer / 1000 / 60 / 60 / 24 / 30)); //月
  const day = parseInt((timer / 1000 / 60 / 60 / 24)); //日
  let hours = parseInt((timer / 1000 / 60 / 60 % 24)); //时
  let minutes = parseInt((timer / 1000 / 60 % 60)); //分
  let seconds = parseInt((timer / 1000 % 60)); //秒
  hours = hours < 0 ? '0' + hours : hours;
  minutes = minutes < 0 ? '0' + minutes : minutes;
  seconds = seconds < 0 ? '0' + seconds : seconds;
  
  let str = '';
  if (mouth > 0) {
    str = mouth + '月' + day + '天' + hours + '时' + minutes + '分' + seconds + '秒';
  } else if (day > 0) {
    str = day + '天' + hours + '时' + minutes + '分' + seconds + '秒';
  } else if (hours > 0) {
    str = hours + '时' + minutes + '分' + seconds + '秒';
  } else if (minutes > 0) {
    str = minutes + '分' + seconds + '秒';
  } else {
    str = seconds + '秒';
  }
  return str
}
const getDomainWithoutPort = (href) => {
	// 正则表达式匹配URL的协议、域名和端口号
	const regex = /^(https?:\/\/)?([^\/:]+)(:\d+)?(\/.*)?$/i;
	// 执行匹配并提取域名
	const matches = href.match(regex);
	if (matches && matches[2]) {
	  return matches[2];
	}
	return '';
}
export default {
  parseNum,
  parseTime,
  formatRichText,
  timeDifference,
  getDomainWithoutPort
}
